<template>
    <el-row :gutter="20" style="margin:10px -5px;min-height:500px" type="flex">
      <el-col style="width:280px">
        <a-input-search style="margin-bottom: 8px" placeholder="请输入查询内容" @change="onChange" />
        <a-tree
          showLine
          @expand="onExpand"
          :expandedKeys="expandedKeys"
          :autoExpandParent="autoExpandParent"
          :treeData="gData"
          :replaceFields="replaceFields"
          @select="this.onSelect"
        >
          <template slot="title" slot-scope="{title,key,providerId}">
            <span v-if="title.indexOf(searchValue) > -1">
              {{title.substr(0, title.indexOf(searchValue))}}
              <span style="color: #f50">{{searchValue}}</span>
              {{title.substr(title.indexOf(searchValue) + searchValue.length)}}
            </span>
            <span v-else>{{title}}</span>
            <a-dropdown :trigger="['click']" v-if="!providerId">
                <a-icon type="bars" style="color:#409EFF"/>
                <a-menu slot="overlay">
                  <a-menu-item @click.native="handleEditRole">
                    <a-icon  type="edit" />修改名称
                  </a-menu-item>
                  <a-menu-item @click.native="handleCanleRole(key)">
                    <a-icon  type="delete" />删除角色
                  </a-menu-item>
                </a-menu>
              </a-dropdown>
          </template>
        </a-tree>
      </el-col>
      <el-col :span="18" style="border-left: #e9e9e9 solid 1px;min-height:500px">
        <el-row>
          <el-col :span="24" style="text-align: right">
            <span style="line-height:32px;float:left">{{roleName}}</span>
            <el-button size="small" @click="handleEditRole">修改角色名称</el-button>
            <el-button size="small" @click="handleAddRole">添加角色</el-button>
          </el-col>
          <el-col :span="24" style="margin: 15px 0 8px 0;padding: 8px;background: rgba(240,240,240,0.65)">
            <el-button size="small" :type="typeTab == '1'?'primary':''" @click="handleTab('1')">功能权限</el-button>
            <el-button size="small" :type="typeTab == '2'?'primary':''" @click="handleTab('2')">当前人员清单</el-button>
          </el-col>
          
          <el-col :span="24" v-show="typeTab == '1'">
            <el-table
            v-loading="loading"
            :data="dataList"
            ref="mokuai"
            border>
              <el-table-column
                prop="name"
                width="180"
                label="模块">
                <template slot-scope="scope">
                  <el-checkbox v-model="scope.row.status" @change="changeStaus('child',scope.row.status,scope.row)">{{scope.row.name}}</el-checkbox>
                </template>
              </el-table-column>
              <!-- <el-table-column
                prop="url"
                width="120"
                label="全选">
                <template slot-scope="scope">
                  <el-checkbox v-model="scope.row.status"></el-checkbox>
                </template>
              </el-table-column> -->
              <el-table-column
                prop="order"
                label="分配功能">
                <template slot-scope="scope">
                  <!-- <div>
                    <el-checkbox>全选</el-checkbox>
                  </div> -->
                  <el-checkbox @change="changeStaus('child',item.status,item,scope.row)" v-model="item.status" v-for="(item, index) in scope.row.children" :key="index">{{item.name}}</el-checkbox>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
          <el-col :span="24" v-show="typeTab == '2'">
            <el-table
            :data="dataList"
            border
            ref="user"
            v-loading="loading">
              <el-table-column
                prop="name"
                label="姓名">
              </el-table-column>
              <el-table-column
                prop="mobile"
                label="手机号">
              </el-table-column>
              <el-table-column
                prop="username"
                label="登录账号">
              </el-table-column>
              <el-table-column
                prop="email"
                label="邮箱">
              </el-table-column>
              <el-table-column
                width="120"
                label="操作"
                align="center">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" @click="handleRemove(scope.row)">移除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <pages v-show="typeTab == '2'" :parames="parames" @render="checkPage"></pages>

          </el-col>
        </el-row>
      </el-col>
      <organizationDialog  :organizationData="organizationData" @checkRender="checkRender"></organizationDialog>

    </el-row>
</template>
<script>
  import organizationDialog from './editOrganization'
  const gData = [];

  const getParentKey = (key, tree) => {
    let parentKey;
    for (let i = 0; i < tree.length; i++) {
      const node = tree[i];
      if (node.children) {
        if (node.children.some(item => item.key === key)) {
          parentKey = node.key;
        } else if (getParentKey(key, node.children)) {
          parentKey = getParentKey(key, node.children);
        }
      }
    }
    return parentKey;
  };
  export default {
    data() {
      return {
        loading: false,
        parames: {
          roleId: '',
          start: 1, //页码index
          limit: 10, //页码最大
          total: 0,
        },
        roleName: '',
        typeTab: '1', //默认tab页在功能权限
        expandedKeys: [],
        searchValue: '',
        autoExpandParent: true,
        gData,
        replaceFields: {
          children: 'roleVoList'
        },
        tableList: [],
        dataList: [],
        start: 1, //页码index
        limit: 10, //页码最大树
        total: 0,
        treeList: [],
        input3: '',
        organizationData: {
          roleName: '',
          type: '',
          title: '',
          show: false,
        }
      };
    },
    methods: {
      checkPage () { //页码改变
        this.postProviderPersonnelListByRole()
      },
      onExpand(expandedKeys) {
        this.expandedKeys = expandedKeys;
        this.autoExpandParent = false;
      },
      handleTab (type) {
        if (this.organizationData.id) {
          if(type == '1') {
            this.typeTab = '1'
            this.postProviderRoleToMenuQueryRoleMenusToTree()
          } else if (type == '2') {
            this.typeTab = '2'
            this.postProviderPersonnelListByRole()
          }
        }
      },
      handleRemove (row) { //移除角色下的用户
        this.$post(this.$api.postProviderUserToRoleDel,{
          roleId: this.organizationData.id, //角色ID
          userId: row.id, //用户ID
        }).then(response => {
          if (response.data.succeed) {
            this.$message({message: '操作成功',type: 'success'})
            setTimeout(() => {
              this.postProviderPersonnelListByRole()
            }, 200);
          }
        })
      },
      changeStaus (type,key,item,childrow) { //处理角色菜单
        if(type == 'child') {
          if (key) { //勾选中
            this.$post(this.$api.postProviderRoleToMenuAdd,{
              roleId: this.organizationData.id, //角色ID
              menuId: item.id, //菜单ID
            }).then(response => {
              if (response.data.succeed) {
                this.$message({message: '操作成功',type: 'success'})
              }
            })
            if (childrow) { //子级的勾选选中
              let n = 0
              childrow.children.forEach(el=>{
                if (el.status) {
                  n = n + 1
                }
              })
              if (n == childrow.children.length && !childrow.status) { //子级都选中父级没选中
                this.$post(this.$api.postProviderRoleToMenuAdd,{
                  roleId: this.organizationData.id, //角色ID
                  menuId: childrow.id, //菜单ID
                }).then(response => {
                  if (response.data.succeed) {
                    childrow.status = true
                  }
                })
              }
            }
          } else { //取消勾选
            this.$post(this.$api.postProviderRoleToMenuDel,{
              roleId: this.organizationData.id, //角色ID
              menuId: item.id, //菜单ID
            }).then(response => {
              if (response.data.succeed) {
                this.$message({message: '操作成功',type: 'success'})
              }
            })
            if (childrow) { //子级的都不选中父级取消选中
              let n = 0
              childrow.children.forEach(el=>{
                if (el.status) {
                  n = n + 1
                }
              })
              if (n == 0 && childrow.status) { //子级都选中父级没选中
                this.$post(this.$api.postProviderRoleToMenuDel,{
                  roleId: this.organizationData.id, //角色ID
                  menuId: childrow.id, //菜单ID
                }).then(response => {
                  if (response.data.succeed) {
                    childrow.status = false
                  }
                })
              }
            }
          }
        }
      },
      handleCanleRole (key) { //删除角色
        this.$post(this.$api.postProviderPersonelRoleDel,{
          roleId: key
        }).then(response => {
          if (response.data.succeed) {
            this.getTree()
          }
        })
      },
      checkRender () {
        this.getTree()
      },
      handleAddMenu () { //添加菜单
        this.organizationData.show = true
      },
      handleEditRole () { //修改角色名称
        if (this.organizationData.roleName == '') {
          this.$alert('请选择角色','提示')
          return false
        }
        this.organizationData.title = '修改角色名称'
        this.organizationData.type = 'editRole'
        this.organizationData.show = true
      },
      handleAddRole () { //添加角色
        this.organizationData.type = 'newRole'
        this.organizationData.title = '添加角色'
        this.organizationData.show = true
      },
      generateList (data) {
        for (let i = 0; i < data.length; i++) {
          const node = data[i];
          const key = node.key;
          this.treeList.push({ key, title: node.title });
        }
      },
      onSelect(selectedKeys, info) { //点击树节点获取当前点击的数据
        if(selectedKeys.length != 0 && info.selectedNodes[0].data.props.dataRef.id) {
          var node = info.selectedNodes[0].data.props.dataRef //数据
          this.organizationData.id = node.id //部门id
          this.organizationData.roleCode = node.roleCode //父级id
          this.organizationData.roleName = node.roleName //服务商id
          this.roleName = node.roleName
          if(this.typeTab == '1') {
            this.postProviderRoleToMenuQueryRoleMenusToTree()
          } else if (this.typeTab == '2') {
            this.typeTab = '2'
            this.postProviderPersonnelListByRole()
          }
        } else {
          this.roleName = ''
          this.dataList = []
        }
      },
      onChange(e) {
        const value = e.target.value;
        const expandedKeys = this.treeList.map(item => {
            if (item.title.indexOf(value) > -1) {
              return getParentKey(item.key, this.gData);
            }
            return null;
          })
          .filter((item, i, self) => item && self.indexOf(item) === i);
        Object.assign(this, {
          expandedKeys,
          searchValue: value,
          autoExpandParent: true,
        });
      },
      postProviderPersonnelListByRole () { //查询角色下的用户
        this.loading = true
        this.dataList = []
        this.parames.roleId = this.organizationData.id
        this.$post(this.$api.postProviderPersonnelListByRole,this.parames).then(response => {
          if (response.data.succeed) {
            this.dataList = response.data.data
            this.parames.total = response.data.totalCount
            setTimeout(() => {
              this.loading = false
            }, 200);
          }
        })
      },
      postProviderRoleToMenuQueryRoleMenusToTree () { 
        this.loading = true
        this.dataList = []
        this.$post(this.$api.postProviderRoleToMenuQueryRoleMenusToTree,{ //查询角色下的菜单树
          roleId: this.organizationData.id
        }).then(response => {
          if (response.data.succeed) {
            this.dataList = response.data.data
            setTimeout(() => {
              this.loading = false
            }, 200);
          }
        })
      },
      getTree() { //获取树
        this.$post(this.$api.postProviderPersonelRoleQueryList).then(response => {
          if (response.data.succeed) {
            this.gData = []
            if (response.data.data.length > 0) {
              response.data.data.forEach(el=>{
                this.getData(el)
                if (el.providerName) {
                  this.gData.push(el)
                }
              })
              this.generateList(this.gData)
            }
          }
        })
          console.log(this.gData)

      },
      getData(data) { //处理树数据
        // if (data.roleName) {
          if (data.providerName) {
            data.title = data.providerName
            data.key = data.providerId //
          } else {
            data.title = data.roleName
            data.key = data.id //
          }
          data.scopedSlots = { title: 'title', key: 'key', providerId: 'providerId' }
          if (data.roleVoList && data.roleVoList.length > 0) {
            for(var i = 0; i < data.roleVoList.length; i++) {
              this.getData(data.roleVoList[i])
            }
          }
        }
      // }
    },
    mounted() {
      this.getTree()
    },
    components: {
      organizationDialog
    }
  };
</script>
